package com.atguigu.serviceedu.service.impl;

import com.atguigu.servicebase.exception.GuliException;
import com.atguigu.serviceedu.entity.EduChapter;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.entity.chapter.ChapterVo;
import com.atguigu.serviceedu.entity.chapter.VideoVo;
import com.atguigu.serviceedu.mapper.EduChapterMapper;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author JY
 * @since 2021-01-19
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getListByCourseId(String courseId) {
        //根据课程Id得到所有章节信息
        QueryWrapper<EduChapter> cWrapper = new QueryWrapper<>();
        cWrapper.eq("course_id",courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(cWrapper);
        //根据课程Id得到所有小节信息
        QueryWrapper<EduVideo> vWrapper = new QueryWrapper<>();
        vWrapper.eq("course_id",courseId);
        List<EduVideo> eduVideos = videoService.list(vWrapper);

        List<ChapterVo> list = new ArrayList<>();

        //封装章节信息
        for (EduChapter eduChapter : eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            List<VideoVo> children = new ArrayList<>();
            //封装小节信息
            for (EduVideo eduVideo : eduVideos) {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo,videoVo);
                children.add(videoVo);
            }
            chapterVo.setChildren(children);
            list.add(chapterVo);
        }


        return list;
    }

    @Override
    public boolean deleteById(String id) {
        //检查这个章节下面是否有小节,有的话不能删除
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",id);
        int count = videoService.count(wrapper);
        if(count>0){
            throw new GuliException(20001,"该分章节下存在视频课程，请先删除视频课程");
        }
        //没用执行删除
        int delete = baseMapper.deleteById(id);
        return delete>0;
    }

    @Override
    public void deleteByCourseId(String id) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",id);
        baseMapper.delete(wrapper);
    }
}
